from hashlib import md5
import os


class Server:
    def __init__(self, main_dict=None):
        # 传入参数的默认值
        if main_dict is None:
            main_dict = {"dirs": ["."], "file_type": [".jar"], "version": "1.0"}
        # 基本参数
        self.main_dict = main_dict
        # 临时参数(声明供函数间使用)
        self.tmp_basic_list = []

    # 遍历匹配函数
    def GetFileList(self, dir_name):
        # 遍历文件进行匹配
        for file in os.listdir(dir_name):
            # 匹配成功便添加
            if not os.path.isdir(file):
                if os.path.splitext(file)[1] in self.main_dict["file_type"]:
                    file_path = dir_name + "/" + file
                    # 获取文件哈希值
                    with open(file_path, "rb") as f:
                        md5Obj = md5()
                        md5Obj.update(f.read())
                        fHash = md5Obj.hexdigest()
                    self.tmp_basic_list.append([file_path, fHash])

    # 更新字典内容函数
    def createDict(self):
        # 对于列表切勿使用a = b形式，会关联起来
        self.tmp_basic_list = []
        # 遍历各目录进行匹配
        for dir_name in self.main_dict["dirs"]:
            # 注意文件夹是否存在
            if os.path.isdir(dir_name):
                self.GetFileList(dir_name)
        # 遍历结果写入字典
        self.main_dict["basic"] = self.tmp_basic_list
        self.main_dict["type"] = "info"
        return self.main_dict
